<template>
    <div class="role-manage">
        <!-- 面包屑和标题 -->
        <el-breadcrumb separator="/" class="mb-2">
            <el-breadcrumb-item>系统管理</el-breadcrumb-item>
            <el-breadcrumb-item>系统基础管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色管理</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="page-title">角色管理</div>

        <!-- 查询区 -->
        <div class="search-area">
            <el-input v-model="query.roleName" placeholder="角色名称" clearable style="width: 220px;" />
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="danger" @click="onBatchDelete" :disabled="!selected.length" class="ml-2">批量删除</el-button>
            <el-button type="primary" class="new-role-btn" @click="onCreateRole">新建角色</el-button>
        </div>

        <!-- 角色表格 -->
        <el-table :data="tableData" border stripe style="width: 100%" @selection-change="onSelectionChange">
            <el-table-column type="selection" width="40" />
            <el-table-column prop="RoleName" label="角色名称" width="150" />
            <el-table-column prop="IsEnabled" label="状态" width="100">
                <template #default="scope">
                    <div class="status-tag">
                        <span v-if="scope.row.IsEnabled" class="dot enabled"></span>
                        <span v-else class="dot disabled"></span>
                        {{ scope.row.IsEnabled ? '启用' : '禁用' }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="MemberCount" label="成员数量" width="100" />
            <el-table-column prop="Description" label="角色描述" min-width="180" />
            <el-table-column prop="DepartmentName" label="所属部门" width="150" />
            <el-table-column label="操作" width="500">
                <template #default="scope">
                    <el-button type="primary" plain size="small" @click="onSetRole(scope.row)">设置权限</el-button>
                    <el-button type="primary" plain size="small" @click="onAddMember(scope.row)">添加人员</el-button>
                    <el-button type="primary" plain size="small" @click="onEdit(scope.row)">编辑</el-button>
                    <el-button type="primary" plain size="small" @click="onCopy(scope.row)">复制</el-button>
                    <el-button type="primary" plain size="small" @click="onSetStatus(scope.row)">设置状态</el-button>
                    <el-button type="danger" plain size="small" @click="onDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <CustomPagination class="mt-2" :currentPage="pageIndex" :pageSize="pageSize" :totalCount="pageInfo.totalCount"
            :totalPage="pageInfo.totalPage" @size-change="onPageSizeChange" @current-change="onCurrentPageChange" />

        <!-- 新建/编辑角色弹窗 -->
        <el-dialog v-model="roleDialog.visible" :title="roleDialog.isEdit ? '编辑角色' : '新建角色'" width="500px">
            <el-form :model="roleForm" label-width="90px" :rules="roleRules" ref="roleFormRef">
                <el-form-item label="角色名称:" prop="roleName" required>
                    <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="描述:" prop="description">
                    <el-input v-model="roleForm.description" type="textarea" :rows="4" placeholder="请输入角色描述"
                        maxlength="100" show-word-limit />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="roleDialog.visible = false">取消</el-button>
                <el-button type="primary" @click="onSaveRole">保存</el-button>
            </template>
        </el-dialog>

        <!-- 添加成员弹窗 -->
        <el-dialog v-model="memberDialog.visible" title="添加成员" width="500px">
            <div class="add-users-form" style="padding: 10px;">
                <el-form-item label="职务名称:">
                    <el-input v-model="memberDialog.jobTitle" placeholder="请输入职务名称" />
                </el-form-item>
                <el-form-item label="选择成员:" required>
                    <UserSelector multiple placeholder="请选择成员" dialogTitle="从部门树选择成员" />
                </el-form-item>
            </div>
            <template #footer>
                <div class="dialog-footer" style="display: flex; justify-content: flex-end; gap: 10px;">
                    <el-button @click="memberDialog.visible = false">取消</el-button>
                    <el-button type="primary" @click="onAddMemberConfirm">确认</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 权限设置弹窗 -->
        <el-dialog v-model="permissionDialog.visible" title="设置权限" width="1000px" :close-on-click-modal="false">
            <div class="permission-container">
                <div class="permission-header">
                    <el-checkbox v-model="permissionDialog.checkAll" :indeterminate="permissionDialog.isIndeterminate"
                        @change="handleCheckAllChange">
                        全选
                    </el-checkbox>
                </div>
                <el-divider />

                <!-- 表格式布局的权限列表 -->
                <div class="permission-grid">
                    <div v-for="category in permissionDialog.permissionTree" :key="category.id"
                        class="permission-category-container">
                        <div class="category-header">{{ category.label }}</div>
                        <div class="permission-items">
                            <div v-for="permission in category.children" :key="permission.id" class="permission-item">
                                <el-checkbox :model-value="isPermissionChecked(permission.id)"
                                    @change="(val: boolean) => handlePermissionItemCheck(permission.id, val)">
                                    {{ permission.label }}
                                </el-checkbox>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 保留原树形结构，但隐藏它，用于数据处理 -->
                <el-tree ref="permissionTreeRef" :data="permissionDialog.permissionTree" show-checkbox node-key="id"
                    :props="{ label: 'label', children: 'children' }" @check="handlePermissionCheck"
                    style="display: none;" />
            </div>
            <template #footer>
                <div style="text-align: right;">
                    <el-button @click="permissionDialog.visible = false">取消</el-button>
                    <el-button type="primary" @click="onPermissionSubmit">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import request from '@/http/http'
import {
    getRoleList,
    addRole,
    updateRole,
    deleteRole,
    setRolePermission,
    addRoleMembers,
    getRoleMembers,
    setRoleStatus,
    type RoleListParams,
    type RoleItem,
    type RoleListData,
    type AddRoleParams,
    type UpdateRoleParams,
    type SetRolePermissionParams,
    type AddRoleMemberParams,
    type GetRoleMembersParams,
    type RoleMemberItem,
    type RoleMemberListData,
    type SetRoleStatusParams,
    type PermissionItem
} from '@/api/role'
import { getRolePermissionList, getAllPermissions } from '@/api/permission'
import { ElMessage, ElMessageBox } from 'element-plus'
import CustomPagination from '@/components/CustomPagination.vue'
import UserSelector from '@/components/UserSelector.vue'

// 查询参数
const query = reactive({
    roleName: ''
})

// 分页参数
const pageIndex = ref(1)
const pageSize = ref(10)
const pageInfo = reactive({
    totalCount: 0,
    totalPage: 0
})

// 表格数据
const tableData = ref<RoleItem[]>([])
// 多选选中的角色
const selected = ref<RoleItem[]>([])

// 角色表单
const roleFormRef = ref()
const roleForm = reactive({
    id: '',
    roleName: '',
    description: ''
})

// 角色表单校验规则
const roleRules = {
    roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    description: [
        { max: 100, message: '描述不能超过100个字符', trigger: 'blur' },
        {
            validator: (rule: any, value: string, callback: any) => {
                if (value && value.trim() === '') {
                    callback(new Error('描述不能只包含空格'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ]
}

// 角色对话框状态
const roleDialog = reactive({
    visible: false,
    isEdit: false
})

// 成员对话框状态
const memberDialog = reactive({
    visible: false,
    roleId: '',
    jobTitle: '',
    selectedUserIds: [] as number[],
})

// 权限对话框状态
const permissionDialog = reactive({
    visible: false,
    roleId: '',
    roleName: '',
    treeData: [] as any[],
    permissionTree: [] as any[],
    checkedKeys: [] as string[],
    checkAll: false,
    isIndeterminate: false,
    permissionData: [] as any[], // 保存原始权限数据
    checkedPermissions: {} as Record<string | number, boolean> // 用于存储选中状态
})

// 权限树引用
const permissionTreeRef = ref()

// 获取角色列表
const fetchRoleList = async () => {
    try {
        const params: RoleListParams = {
            RoleName: query.roleName || "",
            pageIndex: pageIndex.value,
            pageSize: pageSize.value
        }

        const response = await getRoleList(params) as any;

        const responseData = response.Data as RoleListData

        tableData.value = responseData.Data.map(role => ({
            ...role, // 保留所有原始字段
            id: role.RoleId.toString(), // 兼容现有组件的id字段
            roleName: role.RoleName, // 兼容现有组件的字段名
            status: role.IsEnabled, // 兼容现有组件的字段名
            description: role.Description // 兼容现有组件的字段名
        }))

        pageInfo.totalCount = responseData.TotalCount
        pageInfo.totalPage = responseData.TotalPage
    } catch (error: any) {
        console.error('获取角色列表失败:', error)
        ElMessage.error(error.message || '获取角色列表失败')
        tableData.value = []
        pageInfo.totalCount = 0
        pageInfo.totalPage = 0
    }
}

// 查询按钮点击事件
const onSearch = () => {
    pageIndex.value = 1
    fetchRoleList()
}

// 重置按钮点击事件
const onReset = () => {
    query.roleName = ''
    pageIndex.value = 1
    fetchRoleList()
}

// 多选变化事件
const onSelectionChange = (rows: any[]) => {
    selected.value = rows
}

// 分页大小变化事件
const onPageSizeChange = (newSize: number) => {
    pageSize.value = newSize
    pageIndex.value = 1
    fetchRoleList()
}

// 当前页变化事件
const onCurrentPageChange = (newPage: number) => {
    pageIndex.value = newPage
    fetchRoleList()
}

// 新建角色按钮点击事件
const onCreateRole = () => {
    roleDialog.isEdit = false
    roleForm.id = ''
    roleForm.roleName = ''
    roleForm.description = ''
    roleDialog.visible = true
}

// 编辑角色按钮点击事件
const onEdit = (row: any) => {
    roleDialog.isEdit = true
    roleForm.id = row.RoleId.toString()
    roleForm.roleName = row.RoleName
    roleForm.description = row.Description || ''
    roleDialog.visible = true
}

// 保存角色按钮点击事件
const onSaveRole = async () => {
    roleFormRef.value?.validate(async (valid: boolean) => {
        if (!valid) return

        try {
            if (roleDialog.isEdit) {
                // 编辑现有角色
                const updateParams: UpdateRoleParams = {
                    RoleId: parseInt(roleForm.id),
                    RoleName: roleForm.roleName,
                    Description: roleForm.description
                }

                await updateRole(updateParams);
                ElMessage.success('角色更新成功');
            } else {
                // 创建新角色
                const addParams: AddRoleParams = {
                    RoleName: roleForm.roleName,
                    Description: roleForm.description,
                    IsEnabled: true,  // 默认启用
                    DeptId: 0         // 默认部门ID为0
                }

                await addRole(addParams);
                ElMessage.success('角色创建成功');
            }

            roleDialog.visible = false
            fetchRoleList()
        } catch (error: any) {
            console.error('保存角色失败:', error);
            ElMessage.error(error.message || '保存角色失败');
        }
    })
}

// 删除角色按钮点击事件
const onDelete = (row: any) => {
    ElMessageBox.confirm(`确定要删除角色"${row.RoleName}"吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            // 调用删除角色API，传入roleId参数
            await deleteRole(row.RoleId);
            ElMessage.success('删除成功');
            fetchRoleList(); // 刷新列表
        } catch (error: any) {
            console.error('删除角色失败:', error);
            ElMessage.error(error.message || '删除角色失败');
        }
    }).catch(() => {
        // 用户取消删除，不做任何操作
    })
}

// 设置权限按钮点击事件
const onSetRole = async (row: any) => {
    permissionDialog.roleId = row.RoleId.toString();
    permissionDialog.roleName = row.RoleName;

    // 重置选中状态
    permissionDialog.checkedPermissions = {};
    permissionDialog.checkAll = false;
    permissionDialog.isIndeterminate = false;

    // 显示对话框
    permissionDialog.visible = true;

    try {
        // 获取所有权限数据
        const allPermissionsResponse = await getAllPermissions() as any;
        if (!allPermissionsResponse.IsSuc) {
            throw new Error(allPermissionsResponse.Msg || '获取权限列表失败');
        }

        // 转换权限数据为树结构
        const permissionData = convertNestedPermissionsToTable(allPermissionsResponse.Data || []);
        permissionDialog.permissionTree = permissionData;

        // 获取角色已有的权限
        try {
            const rolePermissionsResponse = await getRolePermissionList(row.RoleId) as any;
            if (rolePermissionsResponse.IsSuc && rolePermissionsResponse.Data) {
                // 提取已选中的权限ID
                const selectedPermissions = extractSelectedPermissionsFromTree(rolePermissionsResponse.Data);

                // 等待DOM更新，确保树组件已经渲染完成
                setTimeout(() => {
                    if (permissionTreeRef.value) {
                        try {
                            // 先清空所有选中状态
                            permissionTreeRef.value.setCheckedKeys([]);

                            // 然后设置新的选中状态
                            permissionTreeRef.value.setCheckedKeys(selectedPermissions);

                            // 初始化选中状态对象
                            const allNodes = getAllPermissionNodes();
                            allNodes.forEach(node => {
                                const nodeId = typeof node.id !== 'undefined' ? node.id :
                                    (node.originalData && typeof node.originalData.PermissionId !== 'undefined' ?
                                        node.originalData.PermissionId : null);
                                if (nodeId) {
                                    permissionDialog.checkedPermissions[nodeId] = selectedPermissions.includes(nodeId);
                                }
                            });

                            // 更新全选状态
                            updateCheckAllStatus();
                        } catch (error) {
                            console.error('设置权限树选中状态失败:', error);
                        }
                    }
                }, 500);
            }
        } catch (error: any) {
            console.error('获取角色权限数据失败:', error);
            ElMessage.warning('获取角色权限数据失败，将显示未选中状态');
        }
    } catch (error: any) {
        console.error('获取权限数据失败:', error);
        ElMessage.error(error.message || '获取权限数据失败');
    }
}

// 转换嵌套的树形权限数据为表格式布局
const convertNestedPermissionsToTable = (permissions: any[]) => {
    // 如果permissions不是数组，返回空数组
    if (!Array.isArray(permissions)) {
        return [];
    }

    // 创建一个Map来存储按Category分组的权限
    const categoryMap = new Map();

    // 处理权限数据
    permissions.forEach(item => {
        if (!item) return; // 跳过无效的权限项

        // 使用item中的Category，如果没有则归为'未分类'
        const category = item.Category || '未分类';

        // 如果该分类不存在，则创建
        if (!categoryMap.has(category)) {
            categoryMap.set(category, {
                id: `category-${category}`,
                label: category,
                children: []
            });
        }

        // 将当前项添加到对应的分类中
        if (item.DisplayName) {
            // 使用PermissionId作为id，如果没有则生成一个唯一id
            // 跳过PermissionId为0的项
            if (item.PermissionId === 0) {
                return;
            }

            const permissionId = item.PermissionId !== undefined ? item.PermissionId :
                `perm-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

            categoryMap.get(category).children.push({
                id: permissionId,
                label: item.DisplayName || `权限${permissionId}`,
                detail: item.DisplayName,
                isPermission: true,
                originalData: item
            });
        }

        // 如果有子权限，则递归处理
        if (item.Children && Array.isArray(item.Children) && item.Children.length > 0) {
            // 递归处理子权限，并将结果合并到当前分类
            item.Children.forEach((child: any) => {
                if (!child) return;

                // 跳过PermissionId为0的子项
                if (child.PermissionId === 0) {
                    // 如果有Children，继续处理子项
                    if (child.Children && Array.isArray(child.Children) && child.Children.length > 0) {
                        child.Children.forEach((grandChild: any) => {
                            if (!grandChild || grandChild.PermissionId === 0) return;

                            const grandChildCategory = grandChild.Category || child.Category || category || '未分类';

                            if (!categoryMap.has(grandChildCategory)) {
                                categoryMap.set(grandChildCategory, {
                                    id: `category-${grandChildCategory}`,
                                    label: grandChildCategory,
                                    children: []
                                });
                            }

                            const permissionId = grandChild.PermissionId !== undefined ? grandChild.PermissionId :
                                `perm-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

                            categoryMap.get(grandChildCategory).children.push({
                                id: permissionId,
                                label: grandChild.DisplayName || `权限${permissionId}`,
                                detail: grandChild.DisplayName,
                                isPermission: true,
                                originalData: grandChild
                            });
                        });
                    }
                    return;
                }

                if (child.DisplayName) {
                    const childCategory = child.Category || category || '未分类';

                    // 确保该分类存在
                    if (!categoryMap.has(childCategory)) {
                        categoryMap.set(childCategory, {
                            id: `category-${childCategory}`,
                            label: childCategory,
                            children: []
                        });
                    }

                    const permissionId = child.PermissionId !== undefined ? child.PermissionId :
                        `perm-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

                    categoryMap.get(childCategory).children.push({
                        id: permissionId,
                        label: child.DisplayName || `权限${permissionId}`,
                        detail: child.DisplayName,
                        isPermission: true,
                        originalData: child
                    });
                }

                // 递归处理更深层级的子权限
                if (child.Children && Array.isArray(child.Children) && child.Children.length > 0) {
                    // 这里可以选择递归调用convertNestedPermissionsToTable，但为了简化，我们直接处理一层
                    child.Children.forEach((grandChild: any) => {
                        if (!grandChild || grandChild.PermissionId === 0) return;

                        const grandChildCategory = grandChild.Category || child.Category || category || '未分类';

                        if (!categoryMap.has(grandChildCategory)) {
                            categoryMap.set(grandChildCategory, {
                                id: `category-${grandChildCategory}`,
                                label: grandChildCategory,
                                children: []
                            });
                        }

                        const permissionId = grandChild.PermissionId !== undefined ? grandChild.PermissionId :
                            `perm-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

                        categoryMap.get(grandChildCategory).children.push({
                            id: permissionId,
                            label: grandChild.DisplayName || `权限${permissionId}`,
                            detail: grandChild.DisplayName,
                            isPermission: true,
                            originalData: grandChild
                        });
                    });
                }
            });
        }
    });

    // 将Map转换为数组
    return Array.from(categoryMap.values());
}

// 检查权限是否被选中
const isPermissionChecked = (permissionId: string | number): boolean => {
    if (permissionId === undefined || permissionId === null) return false;
    return !!permissionDialog.checkedPermissions[permissionId];
}

// 从嵌套的树形数据中提取已选中的权限ID
const extractSelectedPermissionsFromTree = (permissions: any[]) => {
    if (!Array.isArray(permissions)) {
        return [];
    }

    const selectedPermissions: any[] = [];

    // 递归处理嵌套的权限数据
    const processItems = (items: any[]) => {
        items.forEach(item => {
            // 跳过PermissionId为0的项
            if (item && item.PermissionId === 0) {
                // 如果有Children，继续处理子项
                if (item.Children && Array.isArray(item.Children) && item.Children.length > 0) {
                    processItems(item.Children);
                }
                return;
            }

            // 根据后端返回的数据结构，判断权限是否被选中
            if (item && item.PermissionId !== undefined) {
                // 如果是角色权限列表，每个存在的项都是已授权的，或者检查IsGranted字段
                if (item.IsGranted === true || !('IsGranted' in item)) {
                    if (item.PermissionId) { // 确保ID不为0
                        selectedPermissions.push(item.PermissionId);
                    }
                }
            }

            // 递归处理子权限
            if (item && item.Children && Array.isArray(item.Children) && item.Children.length > 0) {
                processItems(item.Children);
            }
        });
    };

    processItems(permissions);
    return selectedPermissions;
}

// 全选/全不选
const handleCheckAllChange = (val: boolean) => {
    if (!permissionTreeRef.value) return;

    // 获取所有权限节点
    const allNodes = getAllPermissionNodes();

    // 创建节点ID数组
    const allNodeIds = allNodes.map(node => {
        return typeof node.id !== 'undefined' ? node.id :
            (node.originalData && typeof node.originalData.PermissionId !== 'undefined' ?
                node.originalData.PermissionId : null);
    }).filter(Boolean);

    // 直接操作树组件
    if (val) {
        // 全选 - 设置树组件所有节点为选中状态
        permissionTreeRef.value.setCheckedKeys(allNodeIds);
    } else {
        // 全不选 - 清空所有选中状态
        permissionTreeRef.value.setCheckedKeys([]);
    }

    // 更新内部状态对象
    allNodes.forEach(node => {
        const nodeId = typeof node.id !== 'undefined' ? node.id :
            (node.originalData && typeof node.originalData.PermissionId !== 'undefined' ?
                node.originalData.PermissionId : null);
        if (nodeId) {
            permissionDialog.checkedPermissions[nodeId] = val;
        }
    });

    // 手动设置全选状态
    permissionDialog.checkAll = val;
    permissionDialog.isIndeterminate = false;
}

// 获取所有权限节点
const getAllPermissionNodes = () => {
    const allNodes: any[] = [];

    const traverseTree = (nodes: any[]) => {
        if (!Array.isArray(nodes)) return;

        nodes.forEach(node => {
            // 判断是否为权限节点
            if (node && (
                node.isPermission ||
                (node.originalData && typeof node.originalData.PermissionId !== 'undefined') ||
                typeof node.id !== 'undefined'
            )) {
                allNodes.push(node);
            }

            // 递归处理子节点
            if (node && node.children && Array.isArray(node.children) && node.children.length > 0) {
                traverseTree(node.children);
            }
        });
    };

    traverseTree(permissionDialog.permissionTree);
    return allNodes;
}

// 权限选择变更
const handlePermissionCheck = () => {
    updateCheckAllStatus()
}

// 更新全选状态
const updateCheckAllStatus = () => {
    if (!permissionTreeRef.value) return;

    try {
        // 获取当前选中的键
        const checkedKeys = permissionTreeRef.value.getCheckedKeys();

        // 获取所有权限节点
        const allNodes = getAllPermissionNodes();
        const allNodeIds = allNodes.map(node => {
            return typeof node.id !== 'undefined' ? node.id :
                (node.originalData && typeof node.originalData.PermissionId !== 'undefined' ?
                    node.originalData.PermissionId : null);
        }).filter(Boolean);

        // 计算状态
        const allSelected = allNodeIds.length > 0 && checkedKeys.length === allNodeIds.length;
        const someSelected = checkedKeys.length > 0 && checkedKeys.length < allNodeIds.length;

        // 更新全选状态
        permissionDialog.checkAll = allSelected;
        permissionDialog.isIndeterminate = someSelected;
    } catch (error) {
        console.error('更新全选状态失败:', error);
    }
}

// 同步树组件的选中状态到界面显示
const syncTreeSelectionToUI = () => {
    if (!permissionTreeRef.value) return;

    // 获取当前选中的键
    const checkedKeys: (string | number)[] = permissionTreeRef.value.getCheckedKeys();

    // 获取所有权限节点
    const allPermissionNodes = getAllPermissionNodes();
    const allNodeIds = allPermissionNodes.map(node => node.id || node.PermissionId).filter(Boolean);

    // 创建一个新的选中状态对象
    const newCheckedPermissions: Record<string | number, boolean> = {};

    // 初始化所有权限为未选中
    allPermissionNodes.forEach(node => {
        const nodeId = node.id || node.PermissionId;
        if (nodeId) {
            newCheckedPermissions[nodeId] = false;
        }
    });

    // 设置选中的权限
    checkedKeys.forEach((key) => {
        if (key) {
            newCheckedPermissions[key] = true;
        }
    });

    // 替换整个选中状态对象，确保Vue能够检测到变化
    permissionDialog.checkedPermissions = { ...newCheckedPermissions };

    // 直接计算全选和部分选中状态
    const allSelected = allNodeIds.length > 0 && checkedKeys.length === allNodeIds.length;
    const someSelected = checkedKeys.length > 0 && checkedKeys.length < allNodeIds.length;

    // 更新全选状态
    permissionDialog.checkAll = allSelected;
    permissionDialog.isIndeterminate = someSelected;
}

// 提交权限设置
const onPermissionSubmit = async () => {
    if (!permissionTreeRef.value) return;

    try {
        // 获取当前选中的键
        const checkedKeys = permissionTreeRef.value.getCheckedKeys();

        // 过滤掉非数字ID和以特定前缀开头的ID
        const validPermissionIds = checkedKeys
            .filter((id: string | number) => {
                const idStr = String(id);
                return !idStr.startsWith('category-') && !idStr.startsWith('perm-') && !isNaN(Number(id));
            })
            .map((id: string | number) => Number(id))
            .filter((id: number) => id !== 0); // 过滤掉ID为0的权限

        // 如果没有选中任何权限，提示用户
        if (validPermissionIds.length === 0) {
            ElMessageBox.confirm('您没有选择任何权限，确定要提交吗？', '提交确认', {
                confirmButtonText: '确定提交',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                await submitPermissions(validPermissionIds);
            }).catch(() => {
                // 用户取消提交，不做任何操作
            });
        } else {
            await submitPermissions(validPermissionIds);
        }
    } catch (error: any) {
        console.error('设置角色权限失败:', error);
        ElMessage.error(error.message || '设置角色权限失败');
    }
}

// 提交权限到后端
const submitPermissions = async (numericIds: number[]) => {
    try {
        // 使用setRolePermission函数设置权限
        const params: SetRolePermissionParams = {
            RoleId: parseInt(permissionDialog.roleId),
            PermissionIds: numericIds.map(id => id.toString()) // 转换为字符串数组以匹配API期望的格式
        }

        const response = await setRolePermission(params);

        ElMessage.success(`角色 "${permissionDialog.roleName}" 的权限设置成功`)
        permissionDialog.visible = false

        // 刷新角色列表，以便更新权限状态
        fetchRoleList()
    } catch (error: any) {
        console.error('设置角色权限失败:', error)
        ElMessage.error(error.message || '设置角色权限失败')
    }
}

// 编辑权限
const onPermissions = (row: any) => {
    ElMessage.info(`编辑角色"${row.RoleName}"的权限功能开发中`)
}

// 设置用户权限
const onUserRights = (row: any) => {
    ElMessage.info(`设置"${row.RoleName}"角色的用户权限功能开发中`)
}

// 批量删除按钮点击事件
const onBatchDelete = () => {
    if (selected.value.length === 0) {
        ElMessage.warning('请选择要删除的角色');
        return;
    }

    // 过滤掉有成员的角色
    const canDeleteRoles = selected.value.filter((role: RoleItem) => role.MemberCount === 0);

    if (canDeleteRoles.length === 0) {
        ElMessage.warning('选中的角色都有成员，无法删除');
        return;
    }

    ElMessageBox.confirm(`确定要删除选中的 ${canDeleteRoles.length} 个角色吗？`, '批量删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            // 逐个删除选中的角色
            const deletePromises = canDeleteRoles.map((role: RoleItem) => deleteRole(role.RoleId));
            await Promise.all(deletePromises);

            ElMessage.success(`成功删除 ${canDeleteRoles.length} 个角色`);
            fetchRoleList(); // 刷新列表
        } catch (error: any) {
            console.error('批量删除角色失败:', error);
            ElMessage.error(error.message || '批量删除角色失败');
        }
    }).catch(() => {
        // 用户取消批量删除，不做任何操作
    });
}

// 复制角色按钮点击事件
const onCopy = (row: any) => {
    // 设置为新建模式，但填充数据
    roleDialog.isEdit = false
    // 不复制ID，因为要创建新角色
    roleForm.id = ''
    // 复制名称和描述，并添加"复制"标识
    roleForm.roleName = `${row.RoleName}(复制)`
    roleForm.description = row.Description || ''
    // 显示弹窗
    roleDialog.visible = true
}

// 设置角色状态按钮点击事件
const onSetStatus = (row: any) => {
    // 计算要设置的新状态 (取反当前状态)
    const newStatus = !row.IsEnabled

    ElMessageBox.confirm(
        `确定要${newStatus ? '启用' : '禁用'}角色"${row.RoleName}"吗？`,
        `${newStatus ? '启用' : '禁用'}确认`,
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            // 调用设置状态API
            const params: SetRoleStatusParams = {
                RoleId: row.RoleId,
                IsEnabled: newStatus
            }
            await setRoleStatus(params)
            ElMessage.success(`${newStatus ? '启用' : '禁用'}成功`)
            fetchRoleList() // 刷新列表
        } catch (error: any) {
            console.error('设置角色状态失败:', error)
            ElMessage.error(error.message || '设置角色状态失败')
        }
    }).catch(() => {
        // 用户取消操作，不做任何处理
    })
}

// 添加成员按钮点击事件
const onAddMember = (row: RoleItem) => {
    memberDialog.roleId = row.RoleId.toString();
    memberDialog.jobTitle = ''; // 重置职务名称
    memberDialog.selectedUserIds = []; // 重置已选用户
    memberDialog.visible = true;
};

// 确认添加成员
const onAddMemberConfirm = async () => {
    if (!memberDialog.selectedUserIds || memberDialog.selectedUserIds.length === 0) {
        ElMessage.warning('请选择至少一个成员');
        return;
    }

    try {
        const params: AddRoleMemberParams = {
            RoleId: parseInt(memberDialog.roleId),
            UserIds: memberDialog.selectedUserIds,
        };

        await addRoleMembers(params);
        ElMessage.success(`成功添加 ${memberDialog.selectedUserIds.length} 名成员到角色`);
        memberDialog.visible = false;
        fetchRoleList(); // 刷新列表以更新成员数量
    } catch (error: any) {
        console.error('添加角色成员失败:', error);
        ElMessage.error(error.message || '添加角色成员失败');
    }
};

// 处理权限项的选择和取消选择
const handlePermissionItemCheck = (permissionId: number | string, checked: boolean) => {
    if (!permissionTreeRef.value || permissionId === undefined || permissionId === null) return;

    // 更新选中状态对象
    permissionDialog.checkedPermissions[permissionId] = checked;

    try {
        // 更新树组件的选中状态
        permissionTreeRef.value.setChecked(permissionId, checked, false);

        // 更新全选状态
        setTimeout(() => {
            updateCheckAllStatus();
        }, 0);
    } catch (error) {
        console.error('更新树组件选中状态失败:', error);
    }
}

// 页面加载时获取数据
onMounted(fetchRoleList)
</script>

<style scoped>
.role-manage {
    background: #fff;
    border-radius: 8px;
    padding: 18px;
    min-height: 600px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
}

.page-title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 18px;
}

.search-area {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    gap: 10px;
}

.search-area .new-role-btn {
    margin-left: auto;
}

.status-tag {
    display: flex;
    align-items: center;
}

.dot {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 5px;
}

.dot.enabled {
    background-color: #67C23A;
}

.dot.disabled {
    background-color: #F56C6C;
}

.mt-2 {
    margin-top: 18px;
}

.mb-2 {
    margin-bottom: 18px;
}

.ml-2 {
    margin-left: 8px;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
}

.member-search {
    display: flex;
    margin-bottom: 16px;
}

.permission-container {
    max-height: 600px;
    overflow-y: auto;
    padding: 20px;
}

.permission-grid {
    display: flex;
    flex-direction: column;
    border: 1px solid #EBEEF5;
    border-radius: 4px;
    margin-top: 20px;
    background-color: #FAFAFA;
}

.permission-category-container {
    width: 100%;
    padding: 20px;
    border-bottom: 1px solid #EBEEF5;
    background-color: #FFF;
    margin-bottom: 2px;
}

.permission-category-container:last-child {
    border-bottom: none;
    margin-bottom: 0;
}

.category-header {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #303133;
    padding-left: 12px;
    border-left: 4px solid #409EFF;
}

.permission-items {
    display: flex;
    flex-wrap: wrap;
    padding: 0 20px;
}

.permission-item {
    width: 50%;
    /* 改为每行两个权限项 */
    margin-bottom: 30px;
    padding-right: 30px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
}

.permission-item .el-checkbox {
    display: flex;
    align-items: center;
}

.permission-item .el-checkbox__label {
    font-size: 14px;
    color: #606266;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 为更好的可读性，添加适当的外边距 */
.el-checkbox {
    margin-right: 8px;
}

/* 修改分割线样式 */
.el-divider {
    margin: 15px 0;
}

.permission-header {
    padding: 5px 0;
}
</style>